#region Using

using System;
using System.Xml;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using System.Web;
using BlogEngine.Core;
using BlogEngine.Core.Web.Controls;

#endregion

[Extension("Creates a link and mouse over for World of Warcraft Items", "1.3", "<a href=\"http://www.jwendl.net\">Justin Wendlandt</a>")]
public class WowItemTooltip
{
    public WowItemTooltip()
	{
		Post.Serving += new EventHandler<ServingEventArgs>(Serving);
		Page.Serving += new EventHandler<ServingEventArgs>(Serving);
        Comment.Serving += new EventHandler<ServingEventArgs>(Serving);
	}

    private static readonly Regex wowregex = new Regex(@"\[wowtext:(.*?)\]|\[wowid:(.*?)\]", RegexOptions.Compiled | RegexOptions.IgnoreCase);
    private static void Serving(object sender, ServingEventArgs e)
	{
        if (!e.Body.Contains("[wowtext:") && !e.Body.Contains("[wowid:"))
            return;

        string WOW_LINK = "<a href=\"http://www.wowhead.com/?item={0}\" target=\"_blank\" class=\"{1}\">{2}</a>";
        foreach (Match match in wowregex.Matches(e.Body))
		{
            string expr = match.Groups[0].Value;
            string id = match.Groups[1].Value.Trim();
            string text = "";
            string quality = "";

            string url = "http://www.wowhead.com/?item={0}&xml";
            if (expr.Contains("wowtext"))
            {
                id = id.Replace("&#39;", "'");
                id = HttpContext.Current.Server.UrlEncode(id);
            }
            else
            {
                id = match.Groups[2].Value.Trim();
            }

            try
            {
                HttpContext context = HttpContext.Current;
                XmlDocument doc = new XmlDocument();
                if (context.Cache["wowitem-" + id.ToString()] != null)
                {
                    doc = (XmlDocument)context.Cache["wowitem-" + id.ToString()];
                }
                else
                {
                    doc.Load(String.Format(url, id));
                    context.Cache["wowitem-" + id.ToString()] = doc;
                }

                XmlNode node = null;
                node = doc.SelectSingleNode("/wowhead/item");
                id = node.Attributes["id"].Value;
                node = doc.SelectSingleNode("/wowhead/item/quality");
                quality = node.Attributes["id"].Value;
                quality = "q" + quality;
                node = doc.SelectSingleNode("/wowhead/item/name");
                text = node.InnerText;
            }
            catch (Exception ex)
            {
                text = "Failed to get Information";
                string foobar = ex.ToString();
            }
         
            string link = string.Format(WOW_LINK, id, quality, text);
            e.Body = e.Body.Replace(expr, link);
		}

        if (e.Location != ServingLocation.Feed)
            AddWowScript();
	}

    private static void AddWowScript()
    {
        HttpContext context = HttpContext.Current;
        if (context.Items["wowitem"] == null)
        {
            System.Web.UI.Page page = (System.Web.UI.Page)context.CurrentHandler;
            string js = "<script src=\"http://www.wowhead.com/widgets/power.js\"></script>";
            page.Header.Controls.Add(new System.Web.UI.LiteralControl(js));
            context.Items["wowitem"] = 1;
        }
    }
}
